I'm getting ClassNotFound exception in BroadcastReceiver - android

I'm trying to use this very simple Service and BroadcastReceiver but I'm getting a
ClassNotFound exception. If I don't use startService things are fine so the problem it's with the receiver. I have registered it in the android manifest file so why do I get the ClassNotFound exception?
I will be using this method of communication for polling a php file and updating a ListView. Is this the appropriate way of communicating (broadcast intent)?
public class MessengerServiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this,MessengerService.class));
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b=intent.getExtras();
if(b==null)
return;
String msg=b.getString("message");
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(msg);
}
}
}
public class MessengerService extends Service {
HttpClient hc;
HttpPost hp;
String s[]={"pratik","harsha","dayal","hritika"};
public MessengerService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
hc=new DefaultHttpClient();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t=new Thread(new Runnable(){
public void run()
{
int k=0;
while(true)
{
Intent i=new Intent("com.pdd.messenger.MyAction");
i.putExtra("message",s[k]);
sendBroadcast(i);
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
}
k=(k+1)%4;
}
}
});
t.start();
return super.onStartCommand(intent, flags, startId);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pdd.messenger"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MessengerServiceActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.pdd.messenger.MyAction"/>
</intent-filter>
</receiver>
<service android:name=".MessengerService"></service>
</application>
</manifest>

Related

How to run a thread that uses an innerclass?

When clicked on the button on activity_main (button1) I would like to test the ChatClientService.
In the method onStartCommand i want to run a thread which uses the innerclass as runnable. This is were it goes wrong: the intent works (log shows aaaaa) and it goes into the run method (log shows aaaaa) but I do not manage to go into the innerclass. Any ideas? (sorry for the logs)
ChatClientService.java
public class ChatClientService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
new Thread( new Runnable() {
#Override
public void run() {
Log.i("aaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaa");
}
}).start();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class ChatClient implements Runnable {
private BufferedWriter bw;
private BufferedReader br;
private boolean running;
public void halt() {
Log.i("DDDDDDDDDDDDDDDDDD","DDDDDDDDDDDDDDDDDD");
running = true;
try {
bw.close();
bw = null;
br.close();
br = null;
} catch (IOException e) {
Log.i("EEEEEEEEEEEEEEEEE","EEEEEEEEEEEEEEEEEEE");
}
}
#Override
public void run() {
Log.i("HHHHHHHHHHHHHHH", "HHHHHHHHHHHHHHH");
try {
running = true;
Socket s = new Socket("<your pc ip>", 9999);
this.br = new BufferedReader(new InputStreamReader(s.getInputStream()));
this.bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String in = null;
while(running && (in = br.readLine()) != null) {
Log.i("CHATCLIENT RECV ", in);
}
} catch (UnknownHostException e) {
e.printStackTrace();
Log.i("FFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFF");
} catch (IOException e) {
e.printStackTrace();
Log.i("GGGGGGGGGGGGG","GGGGGGGGGGG");
}
}
}
}
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void TestChat(View v){
Log.i("cccccccccccccccccccccccccc","cccccccccccccccccccccc");
startService(new Intent(getApplication(), ChatClientService.class));
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="be.howest.mad.lab24.oef1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="be.howest.mad.lab24.oef1.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="be.howest.mad.lab24.oef1.ChatClientService"
android:enabled="true"
android:exported="false" >
</service>
</application>
</manifest>
Thanks in advance!
try this...
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
new Thread(new ChatClient()).start();
return START_NOT_STICKY;
}

AIDL, bind and unbind IExtendedNetworkService Service

I use AIDL interface IExtendedNetworkService to get USSD code. But application only work after reboot device. I tried bindservice after install app but it didn't work. So my problem is how way to bind service without reboot device . This is my code:
interface:
package com.android.internal.telephony;
interface IExtendedNetworkService {
void setMmiString(String number);
CharSequence getMmiRunningText();
CharSequence getUserMessage(CharSequence text);
void clearMmiString();
}
Service
public class CDUSSDService extends Service {
private String TAG = "THANG-NGUYEN";
private boolean mActive = false;
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_INSERT)) {
// activity wishes to listen to USSD returns, so activate this
mActive = true;
Log.d(TAG, "activate ussd listener");
} else if (intent.getAction().equals(Intent.ACTION_DELETE)) {
mActive = false;
Log.d(TAG, "deactivate ussd listener");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {
public void clearMmiString() throws RemoteException {
Log.d(TAG, "called clear");
}
public void setMmiString(String number) throws RemoteException {
Log.d(TAG, "setMmiString:" + number);
}
public CharSequence getMmiRunningText() throws RemoteException {
if (mActive == true) {
return null;
}
return "USSD Running";
}
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user message " + text);
if (mActive == false) {
// listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
// listener is active, so broadcast data and suppress it from
// default behavior
// build data to send with intent for activity, format URI as per
// RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(
getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(
getBaseContext().getString(R.string.uri_param_name),
text.toString()).build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
};
public void onCreate() {
Log.i(TAG, "called onCreate");
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "called onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "called onbind");
// the insert/delete intents will be fired by activity to
// activate/deactivate listener since service cannot be stopped
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
filter.addDataAuthority(
getBaseContext().getString(R.string.uri_authority), null);
filter.addDataPath(getBaseContext().getString(R.string.uri_path),
PatternMatcher.PATTERN_LITERAL);
registerReceiver(receiver, filter);
return mBinder;
}
}
MainActivity:
public class MainActivity extends Activity {
private Button btnCheckUSSD;
private Context mContext;
private IExtendedNetworkService mService;
private EditText inputUSSD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
btnCheckUSSD = (Button) findViewById(R.id.btn_check);
inputUSSD = (EditText) findViewById(R.id.input_ussd);
btnCheckUSSD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!inputUSSD.getText().toString().isEmpty()) {
Intent service = new Intent(
"com.android.ussd.IExtendedNetworkService");
bindService(service, mConnecton, Context.BIND_AUTO_CREATE);
startActivity(new Intent("android.intent.action.CALL", Uri
.parse("tel:" + inputUSSD.getText().toString()
+ Uri.encode("#"))));
}
}
});
}
ServiceConnection mConnecton = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
mService = IExtendedNetworkService.Stub
.asInterface((IBinder) iBinder);
}
};
protected void onDestroy() {
super.onDestroy();
Log.d("THANG-NGUYEN", "onDestroy");
unbindService(mConnecton);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.example.checkussdcode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="info.example.checkussdcode.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="info.example.checkussdcode.service.UssdCodeService"
android:process=":remote" >
<intent-filter>
<action android:name="com.android.ussd.IExtendedNetworkService" >
</action>
</intent-filter>
</service>
<receiver android:name="info.example.checkussdcode.RebootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>

Launching already running activity from service

I am trying to making lock screen so I made Service class n inside it broadcastReceiver, and MainActivity.
its working till screen is off, whn screen is went on that time main activity close and showing exception.
Please help me to solve it.
MyService.java
package com.example.broadcast_receiver;
import android.app.Service;
...
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("[myService]", "onCreate");
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.i("[myService]", "onStart");
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.i("[myService]", "onDestroy");
}
BroadcastReceiver mybroadcast = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
Intent i=new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
context.startActivity(i);
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
}
MainActivity.java
package com.example.broadcast_receiver;
import android.os.Bundle;
...
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("[MainActivity]", "Created");
try{
boolean a=isMyServiceRunning();
if(a==false){
startService(new Intent(this,MyService.class));
}
}catch (Exception e) {
// TODO: handle exception
Log.i("Error", e.getMessage().toString());
Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
AndroidManifest.xml
(No User Permission added)
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name="com.example.broadcast_receiver.MyService"
android:label="#string/app_name"
android:icon="#drawable/ic_launcher" ></service>
<activity
android:name="com.example.broadcast_receiver.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Please help me to solve dis problem.
The error is telling you that you can't call startActivity() from outside of a Activity without setting the Intent flag NEW_TASK. Add Intent.FLAG_ACTIVITY_NEW_TASK TO YOUR Intent before calling startActivity()
Intent i=new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

Live wallpaper stuck forever at "Loading live wallpaper..."

I'm code up a simple wallpaper service, similar to this one(Android app to change wallpaper at regular intervals using Timer).
The wallpaper is stuck forever at "Loading live wallpaper..." although the images I tried to draw are tiny (2kb png).
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.TestWallpaper">
<uses-sdk android:minSdkVersion="15"/>
<uses-feature android:name="android.software.live_wallpaper" />
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:permission="android.permission.BIND_WALLPAPER">
<service android:name=".Wallpaper"
android:label="#string/app_name"
android:icon="#drawable/icon">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data android:name="android.service.wallpaper"
android:resource="#xml/livewallpaper" />
</service>
</application>
</manifest>
And my main class file:
public class Wallpaper extends Service {
Timer mytimer;
int initialStart= 0;
int interval=60000;
Drawable drawable;
WallpaperManager wpm;
int prev=1;
#Override
public void onCreate() {
super.onCreate();
Log.i("TestWallPaper=>", "print");
mytimer=new Timer();
wpm= WallpaperManager.getInstance(Wallpaper.this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mytimer.schedule(new TimerTask() {
#Override
public void run() {
Log.i("TestWallPaper=>", "inside onStartCommand");
if(prev==1){
Log.i("TestWallPaper=>", "prev==1");
drawable = getResources().getDrawable(R.drawable.blue_pin);
prev=2;
}
else if(prev==2){
Log.i("TestWallPaper=>", "prev==2");
drawable = getResources().getDrawable(R.drawable.red_pin);
prev=3;
}
else{
Log.i("TestWallPaper=>", "prev==3");
drawable = getResources().getDrawable(R.drawable.green_pin);
prev=1;
}
Bitmap wallpaper=((BitmapDrawable)drawable).getBitmap();
try {
wpm.setBitmap(wallpaper);
} catch (IOException e) {
Log.e("TestWallPaper=>", "inside onStartCommand");
e.printStackTrace();
}
}
}, initialStart,interval);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
Log.i("TestWallPaper=>", "inside onBind");
return null;
}
}

Starting intentservice over adb fails

When I try to start an IntentService over adb i get tho following error
E/AndroidRuntime( 2418): java.lang.RuntimeException: Unable to instantiate service
com.myCompany.MyPackage.Service: java.lang.InstantiationException:
com.myCompany.MyPackage.Service
when I start a normal service ovre adb, everithing works fine.
What are the reason a cannot start an intentservice over adb?
public class NCService extends IntentService {
public NCService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
NetworkStateReceiver nsr;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "onStartCommand", 0).show();
nsr = new NetworkStateReceiver();
return START_STICKY;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "onCreate", 0).show();
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "onDestroy", 0).show();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
}
}
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<service android:name=".NCService" />
<receiver android:name=".NetworkStateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
Regards
Simon
Your service need a default no-arg constructor, otherwise Android does not know what argument pass as name parameter:
public NCService() {
super("MyNCService");
}

Categories

Resources