1

我在 github https://github.com/onlinux/AndroidBatteryWidget中发现了这个电池小部件。我想创建与应用程序中相同的图表。问题是这是一个小部件,事情有点不同。该小部件有一个带有服务类的类https://github.com/onlinux/AndroidBatteryWidget/blob/master/src/fr/free/onlinux/AndroidBatteryWidget/AndroidBatteryWidgetProvider.javaUpdateService。认为我不需要小部件提供程序,我只使用服务并创建了一个新类,UpdateService.java如下所示:

package com.mypackage.app;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.app.PendingIntent;
import android.app.Service;

public static class UpdateService extends Service {    

public final static String TAG = "Bat";

    //private static final String TAG = AndroidBatteryWidgetProvider.class.getSimpleName();
    public static Boolean debug     = true; 
        BatteryInfo mBI = null;     
        public void updateWidget(Context context, Intent batteryIntent){

            if (debug) Log.i(TAG,"---------- updateWidget");

            SimpleDateFormat formatter = new SimpleDateFormat(" HH:mm:ss ");

            RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.androidbatterywidget_layout);

            updateViews.setTextViewText(R.id.level, "waiting!");

            final int status = batteryIntent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);

            final int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);

            final int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

            updateViews.setTextViewText(R.id.level, "" + level + " %" );

            updateViews.setTextViewText(R.id.time, formatter.format(new Date()));

            final int temperature = batteryIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);

            String tempString= String.format("%.0f°C", new Float(temperature/10));

            if (debug) Log.d(TAG,"BAT:" + tempString + " " + level + "%");

            updateViews.setTextViewText(R.id.temperature, tempString );

            final int voltage = batteryIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);


       Intent i = new Intent(context, AndroidBatteryActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

          /*  updateViews.setTextViewText(R.id.voltage, "" + voltage + " mV" );


            updateViews.setOnClickPendingIntent(R.id.layout ,

                    PendingIntent.getActivity(context, 0, 

                            new Intent(context, AndroidBatteryActivity.class),Intent.FLAG_ACTIVITY_NEW_TASK));


          ComponentName myComponentName = new ComponentName(context, AndroidBatteryWidgetProvider.class);

            AppWidgetManager manager = AppWidgetManager.getInstance(context);

            manager.updateAppWidget(myComponentName, updateViews); */


            //Second, update database in a thread       

            new Thread (new Runnable(){

                public void run(){

                    final Context c=getApplicationContext();

                    DBHelper db = new DBHelper(c);

                    db.record( level, status, plugged );

                    db.deleteOldEntries();

                    db.close();

                    if (debug) Log.i( TAG, "---------- Add record: " + level + " time: "+ Calendar.getInstance().getTimeInMillis() );   

                }
            }).start();


        }

        public void  handleCommand(Intent intent){

            if(mBI == null)

            {
                mBI = new BatteryInfo(this);

//              IntentFilter mIntentFilter = new IntentFilter();

//              mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
//              registerReceiver(mBI, mIntentFilter);

                // After registering mBI, another update is immediately processed.

                // So, skip double update processing.
                return;

            } 
            //update widget views and database

            updateWidget(getApplicationContext(), intent);

        }

        @Override
        public void onStart(Intent intent, int startId) {

            handleCommand(intent);            

        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            if (debug)

                Log.d(TAG, "----------------- onStartCommand");     

            handleCommand(intent);     

            // The service has to be running otherwise the broadcast ACTION_BATTERY_CHANGED wont be received anymore

            // thats why it returns START_STICKY
            return START_STICKY;
        }
        @Override
        public void onDestroy() {

            super.onDestroy();

            try{                
                if(mBI != null) {

                    if (debug)

                    Log.d(TAG, "----------------- onDestroy: unregisterReceiver(mBI)" );
                    unregisterReceiver(mBI);

                }

            }catch(Exception e)

            {Log.e(TAG, "", e);}

        }
        @Override
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
        }
    }   
}

在我的 MainActivity 中,如果单击 go to graph,我创建了一个按钮,所以 onclick

Intent intent = new Intent(context, UpdateService.class);

        context.startService(intent);

现在,发生的事情是我可以从 logCat 接收器中看到并且服务运行良好。但是单击应用程序中的按钮没有任何反应。应用程序退出并且没有任何活动开始。在我写的清单中

<service android:name=".UpdateService" /> 
        <receiver android:name=".BatteryInfo" android:label="BatteryInfo">
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED" /> 
        </intent-filter>
        </receiver>

        <activity
            android:name=".AndroidBatteryActivity"
            android:label="@string/app_name" >
        </activity>
        <activity android:name="org.achartengine.GraphicalActivity" >
        </activity>

编辑:我尝试编辑一点代码,现在添加这部分

 Intent i = new Intent(context, AndroidBatteryActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);

启动 Activity AndroidBatteryActivity 但全黑,什么也没有出现。如果 AndroidBatteryActivity 是这个:

public class AndroidBatteryActivity extends Activity {
    public Intent intent ;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        intent = new BatteryChart().execute(this);
           startActivity(intent);
           finish();
    }

    public void myfinish(){
        Log.i("AndroidBatteryActivity", "finish");
        finish();
    }
}

BatteryChart 是带有 chartengine 的图形类。. 我如何调整我的代码?我怎样才能开始图表?我必须改变什么?谢谢

4

1 回答 1

0

您现在可能已经想出了答案,但无论如何这里是如何做到的:

public class MyBatteryReceiver extends Service {

private int batterylevel = 0;
private String batteryStatus = "";


public final static String TAG = "Bat";
public static Boolean debug     = true; 


private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
            batterylevel = intent.getIntExtra("level", 0);



            final int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);



            final int status = intent.getIntExtra("status",
                    BatteryManager.BATTERY_STATUS_UNKNOWN);
            String strStatus;
            if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
                batteryStatus = "Charging";
            } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
                batteryStatus = "Discharging";
            } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
                batteryStatus = "Not charging";
            } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
                batteryStatus = "Full";
            } else {
                batteryStatus = "";
            }



            new Thread (new Runnable(){
                public void run(){
                    final Context c=getApplicationContext();
                    DBHelper db = new DBHelper(c);
                    db.record( batterylevel, status, plugged );
                    db.deleteOldEntries();
                    db.close();
                    if (debug) Log.i( TAG, "---------- Add record: " + batterylevel + " time: "+ Calendar.getInstance().getTimeInMillis() );    
                }
            }).start();


        }
    }
  };
@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(myReceiver, intentFilter);
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unregisterReceiver(myReceiver);
}

}

这是你的活动

public class AndroidBatteryActivity extends Activity {
public Intent intent ;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_battery_chart);
    intent = new BatteryChart().execute(this);
       startActivity(intent);
       finish();
}

public void myfinish(){
    Log.i("AndroidBatteryActivity", "finish");
    finish();
}
}

您需要从您喜欢的位置启动服务

    Intent intent = new       
    Intent(YourActivity.this,yourpackagename.MyBatteryReceiver.class);
    YourActivity.this.startService(intent);

清单中的这个标签

  <service
        android:name="yourpackagename.MyBatteryReceiver"
        android:label="MyBatteryReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED" />
        </intent-filter>
    </service>

只需将您的代码的类名从 MyBatteryReceiver 更改为 UpdateService

于 2014-07-06T11:28:10.430 回答